/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package action;

import bean.LoginActionFormBean;
import bean.ManageBackupBean;
import dao.FtpInfoCrud;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import model.DataBackup;
import model.LogFile;
import model.OSDetector;
import org.apache.struts.actions.DispatchAction;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
import pojo.FtpInfo;

/**
 *
 * @author javauser
 */

//class that manages backup operation...
public class ManageBackupAction extends DispatchAction 
{
    
    /* forward name="success" path="" */
    private final static String SUCCESS = "backupIt";
    DataBackup dataBackup = new DataBackup();
    private String osslash=null;
    
    /**
     * This is the Struts action method called on
     * http://.../actionPath?method=backupFiles,
     * where "method" is the value specified in <action> element : 
     * ( <action parameter="method" .../> )
     */
    
    //method that backup Supplier files 
    public ActionForward backupFiles(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception 
    {
        
        
       String name= request.getServletContext().getRealPath("winconfig.xml");
        System.out.println(" ===============================name fullpath "+name);
        if(OSDetector.isWindows())
        {
            osslash="\\";
        }
        if(OSDetector.isUnix())
        {
            osslash="/";
        }
        
        LoginActionFormBean loginbean=(LoginActionFormBean) request.getSession().getAttribute("LoginActionFormBean");
        System.out.println("backupFiles ........");
        ManageBackupBean backupBean = (ManageBackupBean)form;
        String filesPath = this.getConfigElement("files-path",name);
        String[] providers = backupBean.getSuppliers();
        for (int i = 0; i < providers.length; i++) 
        {
            FtpInfoCrud ftpdao=new FtpInfoCrud(getDataSource(request, "MyDS").getConnection());
            FtpInfo ftp=ftpdao.getByProviderName(providers[i].trim());
            String fileExtension=ftp.getFileExtension();
            boolean zipresult=dataBackup.zipFile(providers[i].trim(), filesPath , fileExtension,name);   
            String fileName = filesPath + osslash + providers[i].trim()+".zip";
            boolean uploadresult=dataBackup.upLoadFile(backupBean.getHostName(), fileName, backupBean.getFtpUsername(), backupBean.getFtpPassword(),providers[i]+".zip");
            if(zipresult == true && uploadresult == true)
            {
                //LogFile.log(loginbean.getUserName(), " took backup from Providers' Files successfully.");
            }
            else
            {
               // LogFile.log(loginbean.getUserName()," failed to take backup from the files of the providers.");
            }
        }
        return mapping.findForward(SUCCESS);
    }

    /**
     * This is the Struts action method called on
     * http://.../actionPath?method=backupLog,
     * where "method" is the value specified in <action> element : 
     * ( <action parameter="method" .../> )
     */
    
    //method to backup logs...
    public ActionForward backupLog(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception 
    {
        String name= request.getServletContext().getRealPath("winconfig.xml");
        if(OSDetector.isWindows())
        {
            osslash="\\";
        }
        if(OSDetector.isUnix())
        {
            osslash="/";
        }
        LoginActionFormBean loginbean=(LoginActionFormBean) request.getSession().getAttribute("LoginActionFormBean");
        ManageBackupBean backupBean = (ManageBackupBean) form;
        System.out.println("backkupLog ......");
        String logpath = this.getConfigElement("log-path",name);
        String filesPath=this.getConfigElement("files-path",name);
        DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
        java.util.Date d = (java.util.Date) formatter.parse(backupBean.getDate());
        SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
        String date = format.format(d);
        boolean zipresult=dataBackup.zipLog(date, logpath,".txt");
        String fileName = logpath + osslash + date+".zip";
        boolean uploadresult=dataBackup.upLoadLog(backupBean.getHostName(), fileName , backupBean.getFtpUsername(), backupBean.getFtpPassword() ,date+".zip");
        if(zipresult == true && uploadresult == true)
        {
            LogFile.log(loginbean.getUserName(), " took backup from Providers' Files successfully.");
        }
        else
        {
            LogFile.log(loginbean.getUserName()," failed to take backup from the files of the providers.");
        }
        return mapping.findForward(SUCCESS);
    }

    //method to parse XML file and get Supplier Files path and/or Log Files Path
    public String getConfigElement(String elementName,String path) 
    {
        String output = null;
        Document config=null;
        try 
        {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            if(OSDetector.isWindows())
            {
                config = builder.parse(path);
            }
            if(OSDetector.isUnix())
            {
                config = builder.parse("/home/ahmed/NetBeansProjects/trunk/Book Dimension Project/src/java/Configuration/linconfig.xml");
            }
            
            Element pathelement = (Element) config.getElementsByTagName(elementName).item(0);
            output = pathelement.getTextContent();
            System.out.println(" files path is                ppppppppp     "+output);
        } 
        catch (SAXException ex) 
        {
            new LogFile("System", " encountered the following Exception while trying to ZIP the file  and this is the error "+ex.getMessage(),path ); 
            //LogFile.log(" System ", " encountered the following problem while trying to parse the XML File "+ex.getMessage());
            Logger.getLogger(ManageBackupAction.class.getName()).log(Level.SEVERE, null, ex);
        } 
        catch (IOException ex) 
        {
            new LogFile("System", " encountered the following Exception while trying to ZIP the file and this is the error "+ex.getMessage(),path ); 
            //LogFile.log(" System ", " encountered the following problem while trying to parse the XML File "+ex.getMessage());
            Logger.getLogger(ManageBackupAction.class.getName()).log(Level.SEVERE, null, ex);
        } 
        catch (ParserConfigurationException ex) 
        {
            new LogFile("System", " encountered the following Exception while trying to ZIP the file and this is the error "+ex.getMessage(),path ); 
            //LogFile.log(" System ", " encountered the following problem while trying to parse the XML File "+ex.getMessage());
            Logger.getLogger(ManageBackupAction.class.getName()).log(Level.SEVERE, null, ex);
        }
        return output;
    }
}
